package music_store.ms.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sun.el.parser.Token;
import music_store.ms.common.Const;
import music_store.ms.common.ServerResponse;
import music_store.ms.common.TokenCache;
import music_store.ms.dao.UserMapper;
import music_store.ms.pojo.User;
import music_store.ms.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    public ServerResponse<User> login(String username, String password){
        int resultCount =userMapper.checkByUsername(username);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("用户名不存在。");
        }

        User user = userMapper.selectLogin(username, password);
        if (user == null){
            return ServerResponse.createByErrorMessage("用户名密码错误。");
        }

        return ServerResponse.createBySuccess("登录成功！",user);
    }

    public ServerResponse<String> register(User user){
        ServerResponse validResponse = this.checkValid(user.getUsername(), Const.USERNAME);
        if (!validResponse.isSuccess()){
            return validResponse;
        }
        validResponse = this.checkValid(user.getEmail(),Const.EMAIL);
        if (!validResponse.isSuccess()){
            return validResponse;
        }

        user.setRole(Const.Role.ROLE_CUSTOMER);

        int resultCount =userMapper.insert(user);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("注册失败。");
        }
        return ServerResponse.createBySuccess("注册成功。");

    }

    public ServerResponse selectQuestionByUsername(String username) {
        if (username == null){
            return ServerResponse.createByErrorMessage("用户名为空。请输入要查找的用户名。");
        }
        ServerResponse response = this.checkValid(username, Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户名不存在。");
        }
        String question = userMapper.selectQuestionByUsername(username);
        if (StringUtils.isBlank(question)){
            return ServerResponse.createByErrorMessage("找回密码的问题是空的。");
        }
        return ServerResponse.createBySuccess(question);
    }

    public ServerResponse<String> forgetCheckAnswer(String username, String question, String answer) {
        ServerResponse response = this.checkValid(username, Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户名不存在。");
        }
        if (StringUtils.isNoneBlank(username,question,answer)){
            int resultCount = userMapper.CheckAnswer(username, question, answer);
            if (resultCount>0){
                String forgetToken = UUID.randomUUID().toString();
                //简单的拼接。key：username，value：随机的一条值。以此作为返回检测的token。
                TokenCache.setKey(TokenCache.TOKEN_PREFIX+username,forgetToken);
                return ServerResponse.createBySuccess(forgetToken);
            }
            return ServerResponse.createByErrorMessage("问题的答案错误。");
        }
        return ServerResponse.createByErrorMessage("有空参数，请重新输入。");
    }

    public ServerResponse<String> forgetResetPassword(String username,String passwordNew,String forgetToken){
        ServerResponse response = this.checkValid(username, Const.USERNAME);
        if (response.isSuccess()){
            return ServerResponse.createByErrorMessage("该用户名不存在。");
        }
        if (StringUtils.isNoneBlank(passwordNew,forgetToken)){
            String token = TokenCache.getKey(TokenCache.TOKEN_PREFIX+username);
            if (StringUtils.isBlank(token)){
                return ServerResponse.createByErrorMessage("token错误或已过期。");
            }
            if (StringUtils.equals(token,forgetToken)){
                int resultCount = userMapper.updatePasswordByUsername(username,passwordNew);
                if (resultCount > 0){
                    return ServerResponse.createBySuccess("修改密码成功！" );
                }
            }
            else {
                return ServerResponse.createByErrorMessage("修改密码失败。token错误。请重新获取修改密码的token。");
            }
        }
        return ServerResponse.createByErrorMessage("修改密码失败。有空参数。请重新输入。");
    }

    public ServerResponse<String> resetPassword(User user,String passwordOld,String passwordNew){
        String username = user.getUsername();
        int resultCount = userMapper.checkPasswordByUsername(username, passwordOld);
        if (resultCount == 0){
            return ServerResponse.createByErrorMessage("用户名与密码不匹配");
        }
        user.setPassword(passwordNew);
        resultCount = userMapper.updateByPrimaryKeySelective(user);
        if (resultCount > 0){
            return ServerResponse.createBySuccess("修改密码成功！");
        }
        return ServerResponse.createByErrorMessage("修改密码失败。");
    }

    public ServerResponse update_info(User user){
        //username不能被更新。
        //user 的 email也要检测，且更新的email不能与已注册的email冲突。
        ServerResponse checkValid = this.checkValid(user.getEmail(), Const.EMAIL);
        if (!checkValid.isSuccess()){
            return ServerResponse.createByErrorMessage("该邮箱已被注册。请更换邮箱再试。");
        }

        User updatedUser = new User();
        updatedUser.setId(user.getId());
        updatedUser.setEmail(user.getEmail());
        updatedUser.setPhone(user.getPhone());
        updatedUser.setQuestion(user.getQuestion());
        updatedUser.setAnswer(user.getAnswer());

        int resultCount = userMapper.updateByPrimaryKeySelective(updatedUser);
        if (resultCount > 0){
            return ServerResponse.createBySuccess("用户信息更新成功！",updatedUser);
        }
        return ServerResponse.createByErrorMessage("用户信息更新失败。");
    }

    public ServerResponse<User> get_info(int userId){
        User presentUser = userMapper.selectByPrimaryKey(userId);
        if (presentUser == null){
            return ServerResponse.createByErrorMessage("找不到该用户。");
        }
        presentUser.setPassword(StringUtils.EMPTY);
        return ServerResponse.createBySuccess(presentUser);
    }

    @Override
    public ServerResponse<PageInfo> listUser(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> userList = userMapper.selectUserList();
        PageInfo pageInfo = new PageInfo(userList);
        pageInfo.setList(userList);
        return ServerResponse.createBySuccess(pageInfo);
    }

    //查重的一个私有方法。
    private ServerResponse checkValid(String str, String type){
        if (StringUtils.isNotBlank(type)){
            if (Const.USERNAME.equals(type)){
                int resultCount = userMapper.checkUsername(str);
                if (resultCount>0){
                    return ServerResponse.createByErrorCodeMessage(1,"用户名已存在。");
                }
            }
            if(Const.EMAIL.equals(type)){
                int resultCount = userMapper.checkEmail(str);
                if (resultCount >0){
                    return ServerResponse.createByErrorCodeMessage(1,"该邮箱已被注册。");
                }
            }
            return ServerResponse.createBySuccess("校验成功。");
        }
        return ServerResponse.createByErrorMessage("参数错误。");
    }
}
